<?php

namespace App\Services\Game\Other;

use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Game\Platform\Org;
use App\Models\Game\Config\Broadcast\Broadcast;
use App\Models\Game\Common\Dictionary;
use Illuminate\Http\Request;

class BroadcastService extends Service
{
    use DatabaseMysql;

    /**
     * 获取数据列表
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Database\Eloquent\Collection[]|int[]
     */
    public function getList($request)
    {
        $query = Broadcast::query()->where('plat_code', '<>', Org::ALL_CODE);

        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 筛选【时间】
        $this->makeWhereParamDatetime($request, $query);
        // 筛选【是否启用】
        $this->makeWhereParam($request, 'enable', $query);

        // 数据条数
        $total = (clone $query)->count();
        // 排序分页
        $this->makeOrderParam($request, $query)->makePaginationParam($request, $query);
        // 查询数据
        $collection = $query->with(['contents:id,content', 'org:code,name'])->get();

        return [
            $collection,
            $total
        ];
    }

    /**
     * 发布游戏公告
     *
     * @param Request $request
     * @return Broadcast
     */
    public function saveItem(Request $request): Broadcast
    {
        // 验证内容和参数匹配
        Dictionary::validate(
            $request->input('content_ids', []),
            $request->input('content_param', [])
        );

        // 修改或创建数据
        $broadcast = Broadcast::updateOrCreate(
            $request->only(['plat_code']),
            $request->only(['enable', 'expire_time', 'content_param'])
        );

        // 同步关联内容
        $broadcast->contents()->sync($request->input('content_ids', []));

        // 通知游戏端配置修改
        $broadcast->syncGameService();

        // 加载关联内容
        $broadcast->load('contents:id,content');

        return $broadcast;
    }
}
